<template>
  <div class="tree-select">
    <tree-node v-for="node in data" :key="node.value" :node="node" :depth="0" :selected-value="selectedValue"
      :expanded-keys="expandedKeys" @node-click="handleNodeClick" @toggle-expand="handleToggleExpand">
      <!-- 传递图标插槽 -->
      <template #icon="{ node }">
        <slot name="icon" :node="node" />
      </template>
    </tree-node>
  </div>
</template>

<script lang="ts">
import { defineComponent, PropType, ref, watch } from 'vue'
import TreeNode from './tree-node.vue'

export interface TreeNode {
  label: string
  value: string | number
  icon?: string
  children?: TreeNode[]
  [key: string]: any // 允许其他自定义属性
}

export default defineComponent({
  name: 'TreeSelect',

  components: { TreeNode },

  props: {
    // 数据源
    data: {
      type: Array as PropType<TreeNode[]>,
      required: true,
      default: () => []
    },

    // 选中的值
    modelValue: {
      type: [String, Number] as PropType<string | number>,
      default: null
    },

    // 默认展开的节点keys
    defaultExpandedKeys: {
      type: Array as PropType<Array<string | number>>,
      default: () => []
    },

    // 是否默认展开所有节点
    defaultExpandAll: {
      type: Boolean,
      default: false
    }
  },

  emits: ['update:modelValue', 'change', 'expand-change'],

  setup(props, { emit }) {
    const selectedValue = ref<string | number | null>(props.modelValue)
    const expandedKeys = ref<Array<string | number>>([])

    // 初始化展开状态
    const initExpandedKeys = () => {
      if (props.defaultExpandAll) {
        // 展开所有节点
        expandedKeys.value = getAllKeys(props.data)
      } else if (props.defaultExpandedKeys?.length) {
        // 展开指定节点
        expandedKeys.value = [...props.defaultExpandedKeys]
      }
    }

    // 获取所有节点的key（用于展开所有）
    const getAllKeys = (nodes: TreeNode[]): Array<string | number> => {
      let keys: Array<string | number> = []
      nodes.forEach(node => {
        keys.push(node.value)
        if (node.children && node.children.length) {
          keys = keys.concat(getAllKeys(node.children))
        }
      })
      return keys
    }

    // 初始化
    initExpandedKeys()

    // 监听modelValue变化
    watch(() => props.modelValue, (newVal) => {
      selectedValue.value = newVal
    })

    // 处理节点点击
    const handleNodeClick = (node: TreeNode) => {
      selectedValue.value = node.value
      emit('update:modelValue', node.value)
      emit('change', node)
    }

    // 处理展开/折叠
    const handleToggleExpand = (node: TreeNode, isExpanded: boolean) => {
      const key = node.value
      if (isExpanded) {
        if (!expandedKeys.value.includes(key)) {
          expandedKeys.value.push(key)
        }
      } else {
        const index = expandedKeys.value.indexOf(key)
        if (index > -1) {
          expandedKeys.value.splice(index, 1)
        }
      }
      emit('expand-change', node, isExpanded)
    }

    return {
      selectedValue,
      expandedKeys,
      handleNodeClick,
      handleToggleExpand
    }
  }
})
</script>

<style scoped>
.tree-select {
  font-family: Arial, sans-serif;
  user-select: none;
}
</style>